﻿using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using Nakio.Framework.Interfaces;

namespace Nakio.Framework.Communication
{
    [DataContract]
    public class EncryptedCommand
    {
        [DataMember]
        private readonly byte[] _command;
                
        public EncryptedCommand(EncryptToken encryptToken, CommandBase command)
        {          
            var ms = new MemoryStream();
            var bf = new BinaryFormatter();

            bf.Serialize(ms, command);
            _command = encryptToken.Encrypt(ms.ToArray());
        }

        public CommandBase DecryptCommand(EncryptToken encryptToken, IClientCallback clientCallback)
        {
            var _decryptedCommand = encryptToken.Decrypt(_command);
            var memoryStream = new MemoryStream(_decryptedCommand);
            var bf = new BinaryFormatter
                         {
                             AssemblyFormat = FormatterAssemblyStyle.Simple,
                             Binder = new ClientAssemblyBinder(clientCallback, encryptToken),
                             Context =
                                 new StreamingContext(StreamingContextStates.All,
                                                      new SerializeContext(clientCallback, encryptToken))
                         };
            var command = (CommandBase)bf.Deserialize(memoryStream);

            return command;

        }
    }
}